package com.hushan.elevator.controller;

import com.hushan.elevator.model.RiskInfo;
import com.hushan.elevator.security.SecurityUtils;
import com.hushan.elevator.service.RiskInfoService;
import com.hushan.elevator.utils.Result;
import com.hushan.elevator.utils.ResultCode;
import com.hushan.elevator.vo.RegisterVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/sys")
@RestController
@Tag(name="System",description = "系统接口文档")
@PreAuthorize("hasAuthority('admin')")
public class SysController {
    private final RiskInfoService riskService;

    public SysController(RiskInfoService riskService) {
        this.riskService = riskService;
    }

    @Operation(summary = "获取全部风险信息", description = "获取本系统全部风险信息")
    @GetMapping("/risk-info")
    public Result getRisks() {
        List<RiskInfo> riskInfos = riskService.findAllRiskInfos();
        return new Result(ResultCode.SUCCESS,riskInfos);
    }

    @Operation(summary = "创建风险信息", description = "创建一个新的风险信息")
    @PostMapping("/risk-info")
    public Result addRisk(@io.swagger.v3.oas.annotations.parameters.RequestBody RiskInfo risk) {
        try{
            riskService.addRiskInfo(risk);
        }catch (Exception e){
            return new Result(ResultCode.FAIL,"序列号已存在");
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Operation(summary = "根据ID获取风险信息", description = "根据指定的风险ID返回单个风险信息的详细信息")
    @GetMapping("/risk-info/{id}")
    public Result getRiskById(@PathVariable("id") int id) {
        RiskInfo risk = riskService.findRiskInfoById(id);
        if (risk != null) {
            return new Result(ResultCode.SUCCESS, risk);
        } else {
            return new Result(ResultCode.FAIL);
        }
    }

    @Operation(summary = "更新风险信息", description = "根据提供的ID和新的风险信息来更新风险信息")
    @PutMapping("/risk-info/{id}")
    public Result updateRisk(@PathVariable("id") int id, @RequestBody RiskInfo risk) {
        if (risk.getRiskId()!=id){
            return Result.FAIL();
        }
        try{
            riskService.updateRiskInfo(risk);
        }catch (Exception e){
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Operation(summary = "删除风险信息", description = "根据指定的风险ID删除对应的风险信息")
    @DeleteMapping("/risk-info/{id}")
    public Result deleteRisk(@PathVariable("id") int id) {
        try {
            riskService.deleteRiskInfo(id);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.FAIL);
        }
    }

}
